package com.common.utils.interceptor;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.usbkey.service.UsbkeyService;
import com.yc.jpyy.utils.UtilDate;

public class Interceptor implements HandlerInterceptor {
	private static Logger logger = LoggerFactory.getLogger(Interceptor.class);
	@Autowired
	private UsbkeyService usbkeyService;

	
	/*
	 * 在handler方法之后执行
	 * 
	 * 
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
	}

	/*
	 * 在handler方法之前，返回ModelAndView之前执行
	 * 
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	/*
	 * 在handler方法之前执行
	 * 
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        //add yangbo 20180913 增删改操作记录在另一个日志文件中，可能过配置文件关闭（0：开，1：闭）
		if (Config.getISOPENMSG_LOG().equals("0")) {
			String requestURL = request.getServletPath();
			String saveURL = "";
			String actionTime = UtilDate.getDateFormatter();
			String index[] = { "add", "save", "update", "modify", "del", "delete" };
			boolean isSave = false;
			for (int i = 0; i < index.length; i ++) {
				if (requestURL.contains(index[i]))
					isSave = true;
				break;
			}
			if (isSave) {
				saveURL = actionTime + requestURL + request.getParameter("info");
				System.out.println("beginURL" + saveURL + "endURL");
				logger.info("beginURL" + saveURL + "endURL");
			}
		}
		String validFlag = request.getParameter("validFlag");
		String userUKFlag = request.getParameter("userUKFlag");
		String info = request.getParameter("info");
		if (info == null || info.isEmpty()) {
			// 获取流
			InputStream is = request.getInputStream();
			byte[] bytes = new byte[request.getContentLength()];
			int nRead = 1;
			int nTotalRead = 0;
			while (nRead > 0) {
				nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
				if (nRead > 0)
					nTotalRead = nTotalRead + nRead;
			}
			// 读取的字节流转换成字符串
			info = new String(bytes, 0, nTotalRead, "utf-8");
			request.setAttribute("info", info);
		}
		if (validFlag != null && userUKFlag != null && validFlag.equals("1") && userUKFlag.equals("1")) {
			Map<String, Object> paras = new HashMap<String, Object>();
			paras.put("userName", request.getParameter("userName"));
			paras.put("mac", request.getParameter("mac"));
			HandlerDataSource.setDataSource("A1");
			Map<String, Object> val = usbkeyService.queryUsbkeyInfo(paras);
			String code = val.get("returnCode").toString();
			if (code.equals("1")) {
				request.setAttribute("pubKey", val.get("ListData"));
				return true;
			} else if (code.equals("0")) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(val));
				out.flush();
				return false;
			} else {
				return false;
			}
		}else{
			return true;
		}
		/*if (validFlag != null && !validFlag.isEmpty() && validFlag.equals("0")) {
			return true;
		}else{
			Map<String, Object> paras = new HashMap<String, Object>();
			paras.put("userName", request.getParameter("userName"));
			paras.put("mac", request.getParameter("mac"));
			//Map<String, Object> params = Tools.JsonToMap(info);
			//String dbcode = params.get("dbcode").toString();
			HandlerDataSource.setDataSource("A1");
			Map<String, Object> val = usbkeyService.queryUsbkeyInfo(paras);
			String code = val.get("returnCode").toString();
			if (code.equals("1")) {
				request.setAttribute("pubKey", val.get("ListData"));
				return true;
			} else if (code.equals("0")) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				// ServletOutputStream out = response.getOutputStream();
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(val));
				out.flush();
				return false;
			} else {
				return false;
			}
		}*/

	}

}
